/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-04-26 10:59:06
 * @LastEditTime: 2022-04-26 11:38:20
 */

import { Transfer, Tree } from 'antd';
import { arrToTree } from '@/utils';

const isChecked = (selectedKeys: any, eventKey: any) => selectedKeys.indexOf(eventKey) !== -1;

const generateTree = (treeNodes: any = [], checkedKeys: any = [], key: string = 'key') =>
  treeNodes.map(({ children, ...props }: any) => {
    return {
      ...props,
      disabled: props.disSelect || checkedKeys.includes(props[key]),
      children: generateTree(children, checkedKeys, key)
    };
  });

const TreeTransfer = ({ dataSource, targetKeys, fieldNames, ...restProps }: any) => {
  const treeDataSource: any[] = arrToTree(dataSource);
  console.log('tree', dataSource, treeDataSource);

  return (
    <Transfer {...restProps} targetKeys={targetKeys} dataSource={dataSource} showSelectAll={false}>
      {({ direction, onItemSelect, selectedKeys }) => {
        if (direction === 'left') {
          const checkedKeys = [...selectedKeys, ...targetKeys];
          return (
            <Tree
              blockNode
              checkable
              checkStrictly
              defaultExpandAll
              fieldNames={fieldNames}
              checkedKeys={checkedKeys}
              treeData={generateTree(treeDataSource, targetKeys, fieldNames?.key)}
              onCheck={(_, { node: { key } }: any) => {
                onItemSelect(key, !isChecked(checkedKeys, key));
              }}
              onSelect={(_, { node: { key } }: any) => {
                onItemSelect(key, !isChecked(checkedKeys, key));
              }}
            />
          );
        }
      }}
    </Transfer>
  );
};

export default TreeTransfer;
